package com.disc.util;

import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Tonight on 2017/7/17.
 */
public class HttpUtil {

   static Map<String,String> header = new HashMap<>();
    static
    {
        //header.put("Referer","http://cloud.189.cn/main.action");
        header.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36");
        header.put("Connection","keep-alive");
        header.put("Accept-Language","zh-CN,zh;q=0.8");
        //header.put("Host","cloud.189.cn");
    }

    public static String createHttpGet(String url,CloseableHttpClient  httpclient )
    {
        HttpGet httpGet = new HttpGet(url);
        for (Map.Entry<String, String> entry : header.entrySet())
        {
            httpGet.setHeader(entry.getKey(),entry.getValue());
        }
        CloseableHttpResponse response = null;
        String result = null;
        try
        {
            response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                result = EntityUtils.toString(entity);
            }
            EntityUtils.consume(entity);
        }
        catch (Exception e)
        {
           e.printStackTrace();
        }
        finally
        {
           try {
               response.close();
           }catch (Exception e)
           {
               e.printStackTrace();
           }
        }
        return  result;
    }

    public static byte[] createHttpGetInputStream(String url, CloseableHttpClient  httpclient)
    {
        HttpGet httpGet = new HttpGet(url);
        for (Map.Entry<String, String> entry : header.entrySet())
        {
            httpGet.setHeader(entry.getKey(),entry.getValue());
        }
        CloseableHttpResponse response = null;
        byte[] result = null;
        try
        {
            response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                InputStream resultStream =  entity.getContent();
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[120];
                int n = 0;
                while (-1 != (n = resultStream.read(buffer)))
                {
                    output.write(buffer, 0, n);
                }
                result = output.toByteArray();
            }
            EntityUtils.consume(entity);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try {
                response.close();
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return  result;
    }
    public static String createHeikeLoginHttpPost(String url,List<NameValuePair> nvps,CloseableHttpClient  httpclient)
    {
        HttpPost httpPost;
        CloseableHttpResponse response = null;
        String result = null;
        try
        {
             httpPost = new HttpPost(url);
            if(nvps != null)
            {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
            }
            for (Map.Entry<String, String> entry : header.entrySet())
            {
                httpPost.setHeader(entry.getKey(),entry.getValue());
            }
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
            {
                result = response.getFirstHeader("Location").getValue();
            }
            EntityUtils.consume(entity);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try {
                response.close();
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return  result;
    }


    public static String createHttpPost(String url,List<NameValuePair> nvps,CloseableHttpClient  httpclient)
    {
        HttpPost httpPost;
        CloseableHttpResponse response = null;
        String result = null;
        try
        {
            httpPost = new HttpPost(url);
            if(nvps != null)
            {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
            }
            for (Map.Entry<String, String> entry : header.entrySet())
            {
                httpPost.setHeader(entry.getKey(),entry.getValue());
            }
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                result = EntityUtils.toString(entity);
            }
            EntityUtils.consume(entity);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try {
                response.close();
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return  result;
    }

    public static String createHeikeAnalysisHttpPost(String url,List<NameValuePair> nvps,CloseableHttpClient  httpclient)
    {
        HttpPost httpPost;
        CloseableHttpResponse response = null;
        String result = null;
        try
        {
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            for (NameValuePair item : nvps)
            {
                multipartEntityBuilder.addTextBody(item.getName(),item.getValue(), ContentType.create("text/plain", Charset.forName("utf-8")));
                //multipartEntityBuilder.addPart(item.getName(),new StringBody(item.getValue(), ContentType.MULTIPART_FORM_DATA));
            }
            multipartEntityBuilder.addPart("ctl00$ContentPlaceHolder1$FileOpenTorrent",new FileBody(null));
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntityBuilder.setContentType(ContentType.MULTIPART_FORM_DATA);
            HttpEntity reqEntity = multipartEntityBuilder.build();

            httpPost = new HttpPost(url);
            if(nvps != null)
            {
                httpPost.setEntity(reqEntity);
            }
            for (Map.Entry<String, String> entry : header.entrySet())
            {
                httpPost.setHeader(entry.getKey(),entry.getValue());
            }
            httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString() + ";" + "boundary=----WebKitFormBoundarymq7CgkUX9jI9SShI");
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            System.out.println(EntityUtils.toString(entity));
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
            {
                result = response.getFirstHeader("Location").getValue();
            }
            EntityUtils.consume(entity);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try {
                response.close();
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return  result;
    }


    public static PoolingHttpClientConnectionManager getSSLNoCheckConnectionManager() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        SSLContextBuilder builder = SSLContexts.custom();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                return true;
            }
        });
        SSLContext sslContext = builder.build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf)
                .build();

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        return cm;
    }
}
